using System.Text;
using System.IO;
using System.Collections;
using System.Threading;

using Microsoft.SPOT.IO;
using GHIElectronics.NETMF.IO;
using System;
using Microsoft.SPOT;

namespace CobraController
{
  public class SDLogger
  {
    private static string LogPath = @"\SD\log.txt";
    private static PersistentStorage sdPS;
    private static ArrayList LogItems;

    //SDLogger()
    public static void start()
    {
      sdPS = new PersistentStorage("SD");
      sdPS.MountFileSystem();
      Thread.Sleep(2000);
    }

    public static void Write(string Message)
    {

      Thread logWriteThread = new Thread(delegate() { WriteToLog(Message); });
      logWriteThread.Start();
    }

    public static ArrayList Read()
    {
      Thread logReadThread = new Thread(delegate() { ReadFromLog(); });
      logReadThread.Start();
      while (logReadThread.ThreadState == ThreadState.Running) { }
      return LogItems;
    }

    public static void Delete()
    {
      Thread logDeleteThread = new Thread(delegate() { DeleteLogFile(); });
      logDeleteThread.Start();
    }

    public static void EjectSD()
    {
      Thread logEjectThread = new Thread(delegate() { EjectSDCard(); });
      logEjectThread.Start();
    }

    private static void WriteToLog(string Message)
    {
      WriteLogLine(Helpers.date() + Message + ";");
    }

    private static void WriteLogLine(string LogLine)
    {
      using (StreamWriter sw = new StreamWriter(LogPath, true))
      {
        if (sw == null)
        {
          Debug.Print("can't find log file");
        }
        else
        {
          try
          {
            sw.WriteLine(LogLine);
          }
          catch (Exception ex)
          {
            Debug.Print(ex.Message);
          }
        }
      }
    }

    private static ArrayList ReadFromLog()
    {
      if (File.Exists(LogPath))
      {
        LogItems = new ArrayList();
        using (StreamReader SR = new StreamReader(LogPath))
        {
          string Line;
          while ((Line = SR.ReadLine()) != string.Empty)
          {
            LogItems.Add(Line);
          }
        }
      }
      return LogItems;
    }

    private static void DeleteLogFile()
    {
      try
      {
        if (File.Exists(LogPath))
        {
          File.Delete(LogPath);
        }
      }
      catch (Exception e)
      {
        Debug.Print(e.ToString());
      }
    }

    private static void EjectSDCard()
    {
      sdPS.UnmountFileSystem();
      sdPS.Dispose();
    }
  }
}
